<template>
  <a-spin :spinning="confirmLoading">
    <a-row class="top-row">
      <a-col :lg="3" :md="12" :sm="21">
        <a-form-item :colon="false" label="备品备件名称">
          {{ model.name }}
        </a-form-item>
      </a-col>
      <a-col :lg="3" :md="12" :sm="21">
        <a-form-item :colon="false" label="备件编号">
          {{ model.number }}
        </a-form-item>
      </a-col>
      <a-col :lg="3" :md="12" :sm="21">
        <a-form-item :colon="false" label="实时库存">
          {{ model.wsnub }}
        </a-form-item>
      </a-col>
    </a-row>
    <div class="title">
      <a-divider style="border: 2px solid #005ce6" type="vertical"/>
      出库信息
    </div>
    <div v-if="type=='出库'">
      <a-button style="float: left" @click="openModal" icon="plus" type="primary">选择采购单</a-button>
      <j-vxe-table
        class="caigou-table"
        keep-source
        ref="enePurchasingSpareparts"
        :loading="enePurchasingSparepartsTable.loading"
        :columns="enePurchasingSparepartsTable.columns"
        :dataSource="enePurchasingSparepartsTable.dataSource"
        :maxHeight="300"
        :disabled="formDisabled"
        :rowNumber="false"
        :rowSelection="true"
        :toolbar="true"
        @remove="handleTableRemove"
        :toolbarConfig="{btns:['remove']}"
        size="small"
      >
        <span style="margin-left: 8px" slot="toolbarPrefix"></span>
        <div slot="toolbarAfter" class="clearfix"></div>
        <template v-slot:shebei="props">
          <j-popup
            field="device_name"
            org-fields="device_name,id"
            dest-fields="device_name,id"
            code="ene_device"
            :multi="false"
            @input="popupCallback"
          />
        </template>


      </j-vxe-table>
      <!--    view_inventory_sum-->

      <a-form-item :colon="false" label="出库说明">
        <a-textarea v-model="model.illustrate"></a-textarea>
      </a-form-item>
    </div>
    <div v-else>
      <a-button style="margin-bottom: 8px" @click="openModal" icon="plus" type="primary">选择采购单</a-button>

      <a-row>
        <a-col :span="6">
          <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="采购名称">
            <a-input disabled v-model="yiku.purchase_name"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="采购单号">
            <a-input disabled v-model="yiku.purchase_nub"></a-input>
          </a-form-item>
        </a-col>
        </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="原仓库">
            <a-input disabled v-model="yiku.whnamen"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="原库位">
            <a-input disabled v-model="yiku.oldLocation"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="移库数量">
            <a-input-number style="width: 100%" v-model="yiku.nub"></a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="目标库位">
            <a-input @change="changeWH"  allow-clear  @click="selectWH" v-model="yiku.location"  class="ruku-input">
              <a-icon v-if="yiku.location==null||yiku.location==''" :precision="0" :step="1" style="font-size: 24px" slot="suffix" type="ellipsis" ></a-icon>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
            <a-textarea v-model="yiku.illustrate"></a-textarea>
          </a-form-item>
        </a-col>
      </a-row>


    </div>


    <j-popup-onl-report
      ref="jPopupOnlReport"
      code="view_inventory_sum"
      :multi="type=='出库'?true:false"
      sorter=""
      groupId=""
      :param="{spid:model.id==null?'':model.id.toString()}"
      @ok="callBack"
    />
    <SelectWarehouseModal @back="getSelectRow" ref="swhmRef"></SelectWarehouseModal>
  </a-spin>
</template>

<script>
import {getAction, httpAction, postAction} from "@api/manage";
import JPopupOnlReport from '@/components/jeecg/modal/JPopupOnlReport'
import {JVXETypes} from "@comp/jeecg/JVxeTable";
import {JVxeTableModelMixin} from '@/mixins/JVxeTableModelMixin.js'
import {getRefPromise, VALIDATE_FAILED} from "@comp/jeecg/JVxeTable/utils/vxeUtils";
import SelectWarehouseModal from "@views/warehouse/modules/SelectWarehouseModal";
const bpbjColumns = [
  {
    title: '备品备件名称',
    align: "center",
    dataIndex: 'name'
  },
  {
    title: '备品备件编号',
    align: "center",
    dataIndex: 'number'
  },
  {
    title: '规格型号',
    align: "center",
    dataIndex: 'model'
  },
  {
    title: '单位',
    align: "center",
    dataIndex: 'unit_dictText'
  },
  {
    title: '采购数量',
    align: "center",
    dataIndex: 'quantity',

  },
  {
    title: '采购单价（元）',
    align: "center",
    dataIndex: 'price',

  },
]
export default {
  name: "EnePurchasingCheckForm",
  components: {JPopupOnlReport,SelectWarehouseModal},
  mixins: [JVxeTableModelMixin],
  props: {
    type: {
      type: String,
      required: true
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      yiku: {},
      shenpiyijian: "",
      bpbjColumns,
      bpbjDataSource: [],
      bpbjHeji: 0,
      model: {},

      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      confirmLoading: false,
      // 采购单
      enePurchasingSparepartsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '采购名称',
            key: 'psName',
            type: JVXETypes.input,
            disabled: true,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{required: true, message: '${title}不能为空'}],
          },
          {
            title: '采购编号',
            key: 'psNub',
            type: JVXETypes.input,
            disabled: true,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{required: true, message: '${title}不能为空'}],
          },
          {
            title: '仓库',
            key: 'whnamen',
            type: JVXETypes.select,
            options: [],
            disabled: true,
            width: "200px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{required: true, message: '${title}不能为空'}],
          },
          {
            title: '库位',
            key: 'location',
            type: JVXETypes.input,
            width: "150px",
            disabled: true,
            placeholder: '请输入${title}',
            defaultValue: '',
            // wsnub
            validateRules: [{required: true, message: '${title}不能为空',}],
          },
          {
            title: '出库数量',
            key: 'nub',
            type: JVXETypes.inputNumber,
            width: "150px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{
              required: true, message: '${title}不能为空',
              handler({cellValue, row, column}, callback, target) {
                console.log("validateRules", cellValue, row)
                // cellValue 当前校验的值
                // row 当前行数据
                // column 当前列配置
                // callback(flag, message) 方法【必须执行】且只能执行一次。
                //          flag = 是否通过了校验，不填写或者填写 null 代表不进行任何操作
                //          message = 提示的类型，默认使用配置的 message
                // target 行编辑的实例对象                // 示例：
                if (cellValue > row.wsnub) {
                  callback(false, '${title}不能大于库存量(' + row.wsnub + ')') // false = 未通过，可以跟自定义提示
                } else {
                  callback(true) // true = 通过验证
                }
              },
            }],
          },
          {
            title: '使用设备',
            key: 'deviceId',
            type: JVXETypes.slot,
            slotName: 'shebei',
            width: "150px",
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{required: true, message: '${title}不能为空'}],
          },
        ]
      },
      url: {
        add: '/ene/eneOutbound/add',
        yiku: '/ene/enePurchasingManagement/relocation',
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {


  },
  mounted() {

  },
  methods: {
    getSelectRow(value){
      console.log("getSelectRow",value.id)
      this.yiku.location=`${value.prefix}-${value.shelfNub}-${value.layersNub}-${value.positionNub}`
      this.yiku.warehouseLocationId=value.id
     if((value!=""&&value!=null)||this.yiku.nub<=0){
       this.errorText=""
      }
    },
    changeWH(){
      if((this.yiku.location==""||this.yiku.location==null)&&this.yiku.nub>0){
        this.errorText="请选择库位!"
      }else{
        this.errorText=""
      }
    },
    selectWH(){
      this.$refs.swhmRef.visible=true
    },
    // 触发单元格删除事件
    handleTableRemove(event) {
      let deleteIds = event.deleteRows.map(row => row.id)
      this.enePurchasingSparepartsTable.dataSource = this.enePurchasingSparepartsTable.dataSource.filter(e => deleteIds.indexOf(e.id) == -1)
    },
    openModal() {
      if (this.disabled === false) {
        this.$refs.jPopupOnlReport.show()
      }
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      that.confirmLoading = true
      console.log("submit",this.yiku)
      if(this.type=="出库"){
      let data = this.enePurchasingSparepartsTable.dataSource.map(e => (
        Object.assign(e, {id: null, illustrate: this.model.illustrate, deviceId: this.model.deviceId})
      ))

      postAction(this.url.add, data).then(res => {
        if (res.success) {
          that.$message.success(res.message);
          that.$emit('close');
        } else {
          that.$message.warning(res.message);
        }
      }).finally(e => {
        that.confirmLoading = false
      })
      }else{
        let data = this.yiku

        postAction(this.url.yiku, data).then(res => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('close');
          } else {
            that.$message.warning(res.message);
          }
        }).finally(e => {
          that.confirmLoading = false
        })
      }

    },
    check(record) {
      this.model = Object.assign({illustrate: ""}, record)
      this.visible = true
      /*    getAction(this.url.list, {id: record.id}).then(res => {
            this.bpbjDataSource = res.result
          })*/
    },
    popupCallback(str, row) {

      this.model = Object.assign(this.model, {deviceId: row.id});
    },
    callBack(rows) {
      console.log("backrow", rows)
      if (this.type == "移库" && rows.length > 0) {
        this.yiku = {
            whnamen:rows[0].whnamen,
            purchase_name:rows[0].purchase_name,
            purchase_nub:rows[0].purchase_nub,
            purchasingSparepartsId: rows[0].psid,
            nub: 0,
            warehouseLocationId:"",
            location:"",
            illustrate:this.model.illustrate,
            oldLocation:rows[0].location,
            oldWarehouseLocationId:rows[0].whid,
        }
        return
      }

      rows.forEach(column => {
        let row = {}
        row.sparePartsId = column.spid
        row.psId = column.psid
        row.warehouseLocationId = column.whid
        row.psName = column.purchase_name
        row.psNub = column.purchase_nub
        row.whnamen = column.whnamen
        row.location = column.location
        row.wsnub = column.wsnub
        console.log("+++++++++++++++++++++")
        console.log(row)
        this.enePurchasingSparepartsTable.dataSource.push(row)
      })

    },


  }
}
</script>

<style scoped>
.top-row {
  background: #F4F5F7;
  padding: 12px 24px;

}

.title {
  margin: 24px 0 8px 0;
  font-weight: bold;
}

.top-row /deep/ .ant-form-item {
  margin-bottom: 0;
  color: #6B778C
}

.top-row /deep/ .ant-form-item-label {
  line-height: 1;
}

.top-row /deep/ .ant-form-item-control {
  line-height: 1;
  margin-top: 10px;
}

.top-row /deep/ .ant-form-item-label > label {
  color: #6B778C
}

.clearfix {
  clear: both;
  margin-bottom: 8px;
}

.caigou-table /deep/ .j-vxe-toolbar {
  margin-bottom: 0;
}
.ruku-input /deep/ .ant-input{
  background: #F4F5F7;
  caret-color:transparent;
}
/deep/ .ant-input-disabled{
  background: #F4F5F7;
  caret-color:transparent;
}
</style>